//
//  CreateJobSiteAttributesView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/16.
//

import UIKit
import SnapKit
import RxGesture
import RxCocoa
import RxSwift
class CreateJobSiteAttributesView: CreateJobBaseView {
    var viewModel = CreateJobSiteAttributesViewModel()
    //story
    let singleStoryOption = OptionTypeLabel(R.string.localizable.single())
    let multiStoryOption = OptionTypeLabel(R.string.localizable.multi())
    var storyRequiredLabel = ViewFactory.shared.generateRequiredLabel()
    //roof
    let tileRoofOption = OptionTypeLabel(RoofTypeValue.Tile.rawValue)
    let colorbondRoofOption = OptionTypeLabel(RoofTypeValue.Colorbond.rawValue)
    let otherRoofOption = OptionTypeLabel(RoofTypeValue.Other.rawValue)
    //panel type
    let monoPanelTypeOption = OptionTypeLabel(PanelTypeValue.Mono.rawValue)
    let polyPanelTypeOption = OptionTypeLabel(PanelTypeValue.Poly.rawValue)
    let bothPanelTypeOption = OptionTypeLabel(PanelTypeValue.Both.rawValue)
    //phase
    let singlePhaseOption = OptionTypeLabel(PhaseTypeValue.Single.rawValue)
    let twoPhaseOption = OptionTypeLabel(PhaseTypeValue.Two.rawValue)
    let threePhaseOption = OptionTypeLabel(PhaseTypeValue.Three.rawValue)
    //mounting type
    let buildingOrStructureOption = OptionTypeLabel(R.string.localizable.buildingOrStructure())
    let groundMountedorFreeStandOption = OptionTypeLabel(R.string.localizable.groundMountedOrFreeStand())
    var mountingTypeRequiredLabel = ViewFactory.shared.generateRequiredLabel()
    override func setUpContentView() {
        let optionBtnWidth: CGFloat = (APPConfig.WidthForPortrait - Constant.AllOutMargin * 2 - Constant.InternalMargin * 2) / 3//一行三个按钮，每个按钮的宽度
        //story
        let storyTitle = LabelWithRedStarView(R.string.localizable.story())
        self.contentView.addSubview(storyTitle)
        storyTitle.snp.makeConstraints { make in
            make.top.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //
        self.contentView.addSubview(singleStoryOption)
        singleStoryOption.snp.makeConstraints { make in
            make.top.equalTo(storyTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(storyTitle)
            make.height.greaterThanOrEqualTo(0)
            make.width.equalTo(optionBtnWidth)
        }
        //
        self.contentView.addSubview(multiStoryOption)
        multiStoryOption.snp.makeConstraints { make in
            make.top.equalTo(singleStoryOption)
            make.left.equalTo(singleStoryOption.snp.right).offset(Constant.InternalMargin)
            make.height.width.equalTo(singleStoryOption)
        }
        
        //storyRequiredLabel
        self.contentView.addSubview(storyRequiredLabel)
        storyRequiredLabel.snp.makeConstraints { make in
            make.top.equalTo(singleStoryOption.snp.bottom).offset(Constant.RequiredTopMargin)
            make.left.equalTo(storyTitle)
            make.size.greaterThanOrEqualTo(0)
        }
        //System Mounting Type
        let mountingTypeTitle = LabelWithRedStarView(R.string.localizable.systemMountingType())
        self.contentView.addSubview(mountingTypeTitle)
        mountingTypeTitle.snp.makeConstraints { make in
            make.top.equalTo(storyRequiredLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(storyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //
        let buildingOrStructureOptionStandardWidth: CGFloat =  236
        self.contentView.addSubview(buildingOrStructureOption)
        buildingOrStructureOption.snp.makeConstraints { make in
            make.top.equalTo(mountingTypeTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(storyTitle)
            make.height.equalTo(singleStoryOption)
            if optionBtnWidth > buildingOrStructureOptionStandardWidth * Constant.currentSizeScale {
                make.width.equalTo(optionBtnWidth)
            }else{
                make.width.equalTo(buildingOrStructureOptionStandardWidth * Constant.currentSizeScale)
            }
            
        }
        //
        if UIDevice.getCurrentDeviceType() == APPConfig.iPadType {//ipad一行显示两个（System Mounting Type）
            self.contentView.addSubview(groundMountedorFreeStandOption)
            groundMountedorFreeStandOption.snp.makeConstraints { make in
                make.top.equalTo(buildingOrStructureOption)
                make.centerX.equalToSuperview()
                make.height.width.equalTo(buildingOrStructureOption)
            }
            
        }else{//iphone显示两行（System Mounting Type）
            self.contentView.addSubview(groundMountedorFreeStandOption)
            groundMountedorFreeStandOption.snp.makeConstraints { make in
                make.top.equalTo(buildingOrStructureOption.snp.bottom).offset(Constant.InternalMargin)
                make.left.equalTo(storyTitle)
                make.width.greaterThanOrEqualTo(buildingOrStructureOption)
                make.height.equalTo(buildingOrStructureOption)
            }
        }
        //mountingTypeRequiredLabel
        self.contentView.addSubview(mountingTypeRequiredLabel)
        mountingTypeRequiredLabel.snp.makeConstraints { make in
            make.top.equalTo(groundMountedorFreeStandOption.snp.bottom).offset(Constant.RequiredTopMargin)
            make.left.equalTo(storyTitle)
            make.size.greaterThanOrEqualTo(0)
        }
        //Roof
        let roofTitle = ViewFactory.shared.generateLabel(R.string.localizable.roof(),textColor: UIColor(hexStr: Constant.NotRequiredTitleColorHexStr))
        self.contentView.addSubview(roofTitle)
        roofTitle.snp.makeConstraints { make in
            make.top.equalTo(mountingTypeRequiredLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(storyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(tileRoofOption)
        tileRoofOption.snp.makeConstraints { make in
            make.top.equalTo(roofTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(storyTitle)
            make.height.width.equalTo(singleStoryOption)
        }
        self.contentView.addSubview(colorbondRoofOption)
        colorbondRoofOption.snp.makeConstraints { make in
            make.top.equalTo(tileRoofOption)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(singleStoryOption)
        }
        self.contentView.addSubview(otherRoofOption)
        otherRoofOption.snp.makeConstraints { make in
            make.top.equalTo(tileRoofOption)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.width.equalTo(singleStoryOption)
        }
        //panelType
        let panelTypeTitle = ViewFactory.shared.generateLabel(R.string.localizable.panelType(),textColor: UIColor(hexStr: Constant.NotRequiredTitleColorHexStr))
        self.contentView.addSubview(panelTypeTitle)
        panelTypeTitle.snp.makeConstraints { make in
            make.top.equalTo(tileRoofOption.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(storyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(monoPanelTypeOption)
        monoPanelTypeOption.snp.makeConstraints { make in
            make.top.equalTo(panelTypeTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(storyTitle)
            make.height.width.equalTo(singleStoryOption)
        }
        self.contentView.addSubview(polyPanelTypeOption)
        polyPanelTypeOption.snp.makeConstraints { make in
            make.top.equalTo(monoPanelTypeOption)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(singleStoryOption)
        }
        self.contentView.addSubview(bothPanelTypeOption)
        bothPanelTypeOption.snp.makeConstraints { make in
            make.top.equalTo(monoPanelTypeOption)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.width.equalTo(singleStoryOption)
        }
        //phase
        let phaseTitle = ViewFactory.shared.generateLabel(R.string.localizable.phase(),textColor: UIColor(hexStr: Constant.NotRequiredTitleColorHexStr))
        self.contentView.addSubview(phaseTitle)
        phaseTitle.snp.makeConstraints { make in
            make.top.equalTo(monoPanelTypeOption.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(storyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(singlePhaseOption)
        singlePhaseOption.snp.makeConstraints { make in
            make.top.equalTo(phaseTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(storyTitle)
            make.height.width.equalTo(singleStoryOption)
            make.bottom.equalTo(-Constant.AllOutMargin)
        }
        self.contentView.addSubview(twoPhaseOption)
        twoPhaseOption.snp.makeConstraints { make in
            make.top.equalTo(singlePhaseOption)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(singleStoryOption)
        }
        self.contentView.addSubview(threePhaseOption)
        threePhaseOption.snp.makeConstraints { make in
            make.top.equalTo(singlePhaseOption)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.width.equalTo(singleStoryOption)
        }
        self.initBinding()
    }
    private func initBinding(){
        //******Init binding
        //************************************************Story
        //选择single story
        singleStoryOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.story == .SingleStory { return }
            self?.selectStoryType(.SingleStory)
        }).disposed(by: self.disposeBag)
        
        //选择multi story
        multiStoryOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.story == .MultiStory { return }
            self?.selectStoryType(.MultiStory)
        }).disposed(by: self.disposeBag)
        //************************************************mounting type
        //选择mounting type: buildingOrStructureOption
        buildingOrStructureOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.install_on_building == .BuildOnBuiding { return }
            self?.selectMountingType(.BuildOnBuiding)
        }).disposed(by: self.disposeBag)
        //选择mounting type: groundMountedorFreeStandOption
        groundMountedorFreeStandOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.install_on_building == .NotBuildOnBuiding { return }
            self?.selectMountingType(.NotBuildOnBuiding)
        }).disposed(by: self.disposeBag)
        //************************************************Roof
        //选择tile roof
        tileRoofOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.roof == .Tile {
                self?.selectRoofType(.None)
            }else{
                self?.selectRoofType(.Tile)
            }
            
        }).disposed(by: self.disposeBag)
        //选择Colorbond roof
        colorbondRoofOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.roof == .Colorbond {
                self?.selectRoofType(.None)
            }else{
                self?.selectRoofType(.Colorbond)
            }
            
        }).disposed(by: self.disposeBag)
        //选择other roof
        otherRoofOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.roof == .Other {
                self?.selectRoofType(.None)
            }else{
                self?.selectRoofType(.Other)
            }
            
        }).disposed(by: self.disposeBag)
        //************************************************Panel type
        //选择mono panel type
        monoPanelTypeOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.panel_type == .Mono {
                self?.selectPanelType(.None)
            }else{
                self?.selectPanelType(.Mono)
            }
        }).disposed(by: self.disposeBag)
        //选择poly panel type
        polyPanelTypeOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.panel_type == .Poly {
                self?.selectPanelType(.None)
            }else{
                self?.selectPanelType(.Poly)
            }
        }).disposed(by: self.disposeBag)
        //选择both panel type
        bothPanelTypeOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.panel_type == .Both {
                self?.selectPanelType(.None)
            }else{
                self?.selectPanelType(.Both)
            }
            
        }).disposed(by: self.disposeBag)
        //************************************************Phase
        //选择sigle phase
        singlePhaseOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.phase == .Single {
                self?.selectPhaseType(.None)
            }else{
                self?.selectPhaseType(.Single)
            }
        }).disposed(by: self.disposeBag)
        //选择two phase
        twoPhaseOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.phase == .Two {
                self?.selectPhaseType(.None)
            }else{
                self?.selectPhaseType(.Two)
            }
        }).disposed(by: self.disposeBag)
        //选择three phase
        threePhaseOption.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击，不做处理
            if self?.viewModel.phase == .Three {
                self?.selectPhaseType(.None)
            }else{
                self?.selectPhaseType(.Three)
            }
        }).disposed(by: self.disposeBag)
        
    }
    func setData(_ model: CreateJobSiteAttributesViewModel){
        self.viewModel = model
        selectStoryType(self.viewModel.story)
        selectRoofType(self.viewModel.roof)
        selectPanelType(self.viewModel.panel_type)
        selectPhaseType(self.viewModel.phase)
        selectMountingType(self.viewModel.install_on_building)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //
        let storyValid = self.viewModel.rx.observe(String.self, "story_value").map({($0 ?? "").count > 0}).share(replay: 1)
        let installOnBuildingValid = self.viewModel.rx.observe(String.self, "install_on_building_value").map({($0 ?? "").count > 0}).share(replay: 1)
//
        //合并
        let everythingValid = Observable.combineLatest(
            storyValid,
            installOnBuildingValid
          ) { $0 && $1} // 取用户名和密码同时有效
          .share(replay: 1)

        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.continueBtn.enableBtn()
            }else{
                strongSelf.continueBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    //MARK: - 选择story
    private func selectStoryType(_ type: StoryTypeValue){
        self.viewModel.story = type
        self.singleStoryOption.setUnSelect()
        self.multiStoryOption.setUnSelect()
        switch type {
        case .SingleStory:
            self.singleStoryOption.setSelect()
        case .MultiStory:
            self.multiStoryOption.setSelect()
        default:
            break
        }
        self.storyRequiredLabel.text = ""
    }
    //MARK: - 选择roof
    private func selectRoofType(_ type: RoofTypeValue){
        self.viewModel.roof = type
        self.tileRoofOption.setUnSelect()
        self.colorbondRoofOption.setUnSelect()
        self.otherRoofOption.setUnSelect()
        switch type {
        case .Tile:
            self.tileRoofOption.setSelect()
        case .Colorbond:
            self.colorbondRoofOption.setSelect()
        case .Other:
            self.otherRoofOption.setSelect()
        default:
            break
        }
    }
    //MARK: - 选择panel type
    private func selectPanelType(_ type: PanelTypeValue){
        self.viewModel.panel_type = type
        self.monoPanelTypeOption.setUnSelect()
        self.polyPanelTypeOption.setUnSelect()
        self.bothPanelTypeOption.setUnSelect()
        switch type {
        case .Mono:
            self.monoPanelTypeOption.setSelect()
        case .Poly:
            self.polyPanelTypeOption.setSelect()
        case .Both:
            self.bothPanelTypeOption.setSelect()
        default:
            break
        }
    }
    //MARK: - 选择phase type
    private func selectPhaseType(_ type: PhaseTypeValue){
        self.viewModel.phase = type
        self.singlePhaseOption.setUnSelect()
        self.twoPhaseOption.setUnSelect()
        self.threePhaseOption.setUnSelect()
        switch type {
        case .Single:
            self.singlePhaseOption.setSelect()
        case .Two:
            self.twoPhaseOption.setSelect()
        case .Three:
            self.threePhaseOption.setSelect()
        default:
            break
        }
    }
    //MARK: - 选择Mountingv type
    private func selectMountingType(_ type: MountingTypeValue){
        self.viewModel.install_on_building = type
        self.buildingOrStructureOption.setUnSelect()
        self.groundMountedorFreeStandOption.setUnSelect()
        switch type {
        case .BuildOnBuiding:
            self.buildingOrStructureOption.setSelect()
        case .NotBuildOnBuiding:
            self.groundMountedorFreeStandOption.setSelect()
        default:
            break
        }
        self.mountingTypeRequiredLabel.text = ""
    }
}
